<template>
  <div class="tv-home-container">
    <!-- 背景动画 -->
    <div class="background-animation"></div>
    
    <!-- 顶部标题 -->
    <div class="tv-header">
      <div class="header-logo">TV GAMES</div>
    </div>
    
    <!-- 主内容区 -->
    <div class="tv-main-content">
      <h1 class="tv-title">精选游戏合集</h1>
      
      <!-- 房间连接提示弹窗 -->
      <div v-if="showRoomPrompt" class="room-prompt-overlay">
        <div class="room-prompt-modal">
          <h2>检测到游戏房间</h2>
          <p>扫码成功！检测到你想要连接的绘图游戏房间。</p>
          <div class="room-info">
            <p><strong>房间ID:</strong> {{ roomInfo?.roomId }}</p>
            <p><strong>服务器:</strong> {{ roomInfo?.ip }}:{{ roomInfo?.port }}</p>
          </div>
          <div class="room-prompt-buttons">
            <button class="connect-btn" @click="connectToDrawRoom">连接游戏</button>
            <button class="cancel-btn" @click="closeRoomPrompt">稍后连接</button>
          </div>
        </div>
      </div>

      <!-- 游戏卡片轮播 -->
      <div 
  class="game-carousel"
  @touchstart="handleTouchStart"
  @touchmove="handleTouchMove"
  @touchend="handleTouchEnd"
  @mousedown.prevent=""
>
        <div 
          v-for="(game, index) in games" 
          :key="game.id"
          class="game-card"
          :class="getCardClass(index)"
          @click="navigateToGame(game.route)"
          tabindex="0"
          ref="gameCards"
          @keydown.enter="navigateToGame(game.route)"
        >
          <div class="card-image" :style="{ backgroundImage: `url(${game.image})` }"></div>
          <div class="card-content">
            <h2 class="card-title">{{ game.title }}</h2>
            <div class="card-meta">
              <span class="card-category">{{ game.category }}</span>
              <span class="card-rating">⭐ {{ game.rating }}</span>
            </div>
          </div>
        </div>
      </div>
      

    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, onActivated } from 'vue';
import { useRouter, useRoute } from 'vue-router';

const router = useRouter();
const route = useRoute();
const STORAGE_KEY = 'tv-games-carousel-index';
const gameCards = ref<HTMLElement[]>([]);
const activeIndex = ref(parseInt(sessionStorage.getItem(STORAGE_KEY) || '0'));

// 房间连接相关状态
const showRoomPrompt = ref(false);
const roomInfo = ref<{roomId: string, ip: string, port: string} | null>(null);

// 触摸相关状态
const touchStartX = ref(0);
const touchEndX = ref(0);
const touchStartTime = ref(0);
const isDragging = ref(false);
const minSwipeDistance = 50; // 最小滑动距离
const maxSwipeTime = 300; // 最大滑动时间(ms)
const velocity = ref(0); // 滑动速度
const animationId = ref(0); // 动画ID
const dampingFactor = 0.85; // 降低阻尼系数使滑动更流畅
const minVelocity = 0.3; // 提高最小速度阈值使惯性更明显

// 处理触摸开始
const handleTouchStart = (e: TouchEvent) => {
  touchStartX.value = e.touches[0].clientX;
  touchEndX.value = e.touches[0].clientX;
  touchStartTime.value = Date.now();
  isDragging.value = true;
};

// 处理触摸移动
const handleTouchMove = (e: TouchEvent) => {
  if (!isDragging.value) return;
  touchEndX.value = e.touches[0].clientX;
  e.preventDefault(); // 防止页面滚动
};

// 处理触摸结束
const handleTouchEnd = () => {
  if (!isDragging.value) return;
  isDragging.value = false;
  
  const distance = touchEndX.value - touchStartX.value;
  const duration = Date.now() - touchStartTime.value;
  
  // 计算滑动速度
  velocity.value = distance / Math.max(duration, 1);
  
  // 判断是否满足滑动条件
  if (Math.abs(distance) >= minSwipeDistance && duration <= maxSwipeTime) {
    if (distance > 0) {
      // 向右滑动 - 显示左侧项目（上一张）
      activeIndex.value = activeIndex.value > 0 ? activeIndex.value - 1 : games.length - 1;
    } else {
      // 向左滑动 - 显示右侧项目（下一张）
      activeIndex.value = activeIndex.value < games.length - 1 ? activeIndex.value + 1 : 0;
    }
    saveActiveIndex();
    focusActiveCard();
  }
  
  // 启动惯性动画以提供更流畅的体验
  startInertiaAnimation();
};

// 惯性动画
const startInertiaAnimation = () => {
  cancelAnimationFrame(animationId.value);
  
  const animate = () => {
    if (Math.abs(velocity.value) < minVelocity) {
      velocity.value = 0;
      return;
    }
    
    // 应用阻尼效果
    velocity.value *= dampingFactor;
    
    // 根据速度判断是否切换卡片 (降低阈值使更容易触发切换)
    if (Math.abs(velocity.value) > 0.5) {
      if (velocity.value > 0) {
        // 向右滑动 - 显示左侧项目（上一张）
        activeIndex.value = activeIndex.value > 0 ? activeIndex.value - 1 : games.length - 1;
      } else {
        // 向左滑动 - 显示右侧项目（下一张）
        activeIndex.value = activeIndex.value < games.length - 1 ? activeIndex.value + 1 : 0;
      }
      saveActiveIndex();
      focusActiveCard();
      velocity.value = 0; // 停止惯性动画
    }
    
    animationId.value = requestAnimationFrame(animate);
  };
  
  animate();
};

// 保存当前索引到sessionStorage
const saveActiveIndex = () => {
  sessionStorage.setItem(STORAGE_KEY, activeIndex.value.toString());
};

// 游戏数据
const games = [
  {
    id: 'riddle',
    title: '猜谜语',
    description: '测试你的智慧，猜猜这些有趣的谜语',
    route: '/riddle',
    icon: 'LightbulbIcon',
    image: 'https://img.freepik.com/free-vector/chinese-lantern-concept-illustration_114360-7323.jpg',
    category: '益智',
    rating: '4.8'
  },
  {
    id: 'idiom',
    title: '成语接龙',
    description: '一个接一个，看谁的成语储备更丰富',
    route: '/idiom',
    icon: 'ChainIcon',
    image: 'https://img.freepik.com/free-vector/hand-drawn-chinese-idioms-illustration_23-2149642936.jpg',
    category: '文字',
    rating: '4.7'
  },
  {
    id: 'brain-teaser',
    title: '脑筋急转弯',
    description: '挑战你的思维，解开这些有趣的谜题',
    route: '/brain-teaser',
    icon: 'BrainIcon',
    image: 'https://img.freepik.com/free-vector/brain-with-light-bulb-idea-concept_114360-1598.jpg',
    category: '智力',
    rating: '4.9'
  },
  {
    id: 'draw-guess',
    title: '你画我猜',
    description: '一个画，一个猜，考验默契的时候到了',
    route: '/draw-guess',
    icon: 'PencilIcon',
    image: 'https://img.freepik.com/free-vector/hand-drawn-pictionary-illustration_23-2149241987.jpg',
    category: '互动',
    rating: '4.6'
  },
  {
    id: 'couplet-game',
    title: '对对联',
    description: '传统文化，对出下联赢高分',
    route: '/couplet-game',
    icon: 'ScrollIcon',
    image: 'https://img.freepik.com/free-vector/chinese-couplet-traditional-decoration_107791-1803.jpg',
    category: '文字',
    rating: '4.5'
  },
  {
    id: 'settings',
    title: '设置',
    description: '自定义游戏体验，调整数据库和倒计时设置',
    route: '/settings',
    icon: 'SettingsIcon',
    image: 'https://img.freepik.com/free-vector/illustration-gear-wheel-icon_53876-28520.jpg',
    category: '系统',
    rating: '5.0'
  },
  {
    id: 'error-test',
    title: '错误测试',
    description: '测试服务器错误弹窗和状态检查功能',
    route: '/error-test',
    icon: 'TestIcon',
    image: 'https://img.freepik.com/free-vector/bug-fixing-software-testing-computer-virus-searching-error-404-website-page-not-found-antivirus-app-magnifying-glass-cogwheel-vector-isolated-concept-metaphor-illustration_335657-2842.jpg',
    category: '调试',
    rating: '4.0'
  }
];

// 导航到游戏页面
const navigateToGame = (route: string) => {
  router.push(route);
};

/**
 * 连接到绘图游戏房间
 */
const connectToDrawRoom = () => {
  if (roomInfo.value) {
    const { roomId, ip, port } = roomInfo.value;
    const drawGuessUrl = `/drawguess?roomId=${roomId}&ip=${ip}&port=${port}`;
    router.push(drawGuessUrl);
  }
};

/**
 * 关闭房间连接提示
 */
const closeRoomPrompt = () => {
  showRoomPrompt.value = false;
  roomInfo.value = null;
  // 清除URL参数
  router.replace('/');
};

// 处理键盘导航
const handleKeyDown = (event: KeyboardEvent) => {
  const { key } = event;
  
  switch (key) {
    case 'ArrowUp':
      if (activeIndex.value >= 2) {
        activeIndex.value -= 2;
      } else {
        // 循环到倒数第二项
        activeIndex.value = games.length - (2 - activeIndex.value);
      }
      saveActiveIndex();
      focusActiveCard();
      break;
    case 'ArrowDown':
      if (activeIndex.value + 2 < games.length) {
        activeIndex.value += 2;
      } else {
        // 循环到第二项
        activeIndex.value = (activeIndex.value + 2) % games.length;
      }
      saveActiveIndex();
      focusActiveCard();
      break;
    case 'ArrowLeft':
      activeIndex.value = activeIndex.value > 0 ? activeIndex.value - 1 : games.length - 1;
      saveActiveIndex();
      focusActiveCard();
      break;
    case 'ArrowRight':
      activeIndex.value = activeIndex.value < games.length - 1 ? activeIndex.value + 1 : 0;
      saveActiveIndex();
      focusActiveCard();
      break;
  }
};

// 获取卡片的CSS类
const getCardClass = (index: number) => {
  const position = index - activeIndex.value;
  const classes = {
    active: position === 0,
    'left-1': position === -1,
    'left-2': position === -2,
    'left-3': position === -3,
    'right-1': position === 1,
    'right-2': position === 2,
    'right-3': position === 3,
    far: Math.abs(position) > 3
  };
  
  // 处理循环情况
  if (position <= -4) {
    classes['right-3'] = true;
    classes.far = false;
  } else if (position >= 4) {
    classes['left-3'] = true;
    classes.far = false;
  }
  
  return classes;
};

// 聚焦到当前激活的卡片
const focusActiveCard = () => {
  setTimeout(() => {
    gameCards.value[activeIndex.value]?.focus();
  }, 0);
};

onMounted(() => {
  // 检查URL参数，是否来自扫码连接
  const roomId = route.query.roomId as string;
  const ip = route.query.ip as string;
  const port = route.query.port as string;
  const from = route.query.from as string;
  
  if (roomId && ip && port && from === 'drawguess') {
    // 保存房间信息并显示连接提示
    roomInfo.value = { roomId, ip, port };
    showRoomPrompt.value = true;
    console.log('检测到绘图游戏房间信息:', roomInfo.value);
  }
  
  // 添加事件监听
  window.addEventListener('keydown', handleKeyDown);
  
  // 初始聚焦到第一个卡片
  setTimeout(() => {
    gameCards.value[0]?.focus();
  }, 100);
  
  // 获取轮播容器并添加触摸/鼠标事件
  const carousel = document.querySelector('.game-carousel') as HTMLElement;
  if (carousel) {
    // 触摸事件 - 使用类型断言修复事件监听器类型错误
    carousel.addEventListener('touchstart', handleTouchStart as EventListener, { passive: false });
    carousel.addEventListener('touchmove', handleTouchMove as EventListener, { passive: false });
    carousel.addEventListener('touchend', handleTouchEnd as EventListener, { passive: false });
    
    // 声明HTMLElement变量避免类型错误
    const carouselEl = ref<HTMLElement | null>(null);
    
    // 鼠标事件处理函数声明
    const handleMouseStart = (e: Event) => {
      const mouseEvent = e as MouseEvent;
      mouseEvent.preventDefault();
      carouselEl.value = mouseEvent.currentTarget as HTMLElement;
      touchStartX.value = mouseEvent.clientX;
      touchEndX.value = mouseEvent.clientX;
      touchStartTime.value = Date.now();
      isDragging.value = true;
      velocity.value = 0; // 重置速度
      document.addEventListener('mousemove', handleMouseMove as EventListener);
      document.addEventListener('mouseup', handleMouseEnd as EventListener);
    };

    const handleMouseMove = (e: Event) => {
      const mouseEvent = e as MouseEvent;
      if (!isDragging.value) return;
      touchEndX.value = mouseEvent.clientX;
      mouseEvent.preventDefault();
      // 实时预览拖动效果
      const carousel = document.querySelector('.game-carousel') as HTMLElement;
      if (carousel) {
        carousel.style.transform = `translateX(${touchEndX.value - touchStartX.value}px)`;
      }
    };

    const handleMouseEnd = () => {
      // 清除拖动效果
      const carousel = document.querySelector('.game-carousel') as HTMLElement;
      if (carousel) {
        carousel.style.transform = '';
      }
      if (!isDragging.value) return;
      isDragging.value = false;
      document.removeEventListener('mousemove', handleMouseMove as EventListener);
      document.removeEventListener('mouseup', handleMouseEnd as EventListener);
      
      const distance = touchEndX.value - touchStartX.value;
      const duration = Date.now() - touchStartTime.value;
      
      // 计算滑动速度
      velocity.value = distance / Math.max(duration, 1);
      
      // 启动惯性动画
      startInertiaAnimation();
      
      if (Math.abs(distance) >= minSwipeDistance && duration <= maxSwipeTime) {
        if (distance > 0) {
          // 向右拖动 - 显示左侧项目（上一张）
          activeIndex.value = activeIndex.value > 0 ? activeIndex.value - 1 : games.length - 1;
        } else {
          // 向左拖动 - 显示右侧项目（下一张）
          activeIndex.value = activeIndex.value < games.length - 1 ? activeIndex.value + 1 : 0;
        }
        saveActiveIndex();
        focusActiveCard();
      }
    };

    carousel.addEventListener('mousedown', handleMouseStart);
  }
});

onBeforeUnmount(() => {
  // 移除键盘事件监听
  window.removeEventListener('keydown', handleKeyDown);
  // 取消动画
  cancelAnimationFrame(animationId.value);
  saveActiveIndex();
});

// 当从缓存中重新激活组件时恢复索引
onActivated(() => {
  const savedIndex = sessionStorage.getItem(STORAGE_KEY);
  if (savedIndex) {
    activeIndex.value = parseInt(savedIndex);
    focusActiveCard();
  }
});

// 简单的图标组件
// 图标组件已移除，如需要可重新添加


</script>

<style scoped lang="scss">
@use './Home.scss';
</style>
